package com.rfsp.mcp.util;


import java.awt.Color;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.lowagie.text.Cell;
import com.rfsp.common.enums.SystemConst;
import com.rfsp.common.exception.BaseException;
import com.rfsp.common.util.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rfsp.common.shiro.ShiroUtils;
import com.rfsp.mcp.enums.McpConst;
import com.rfsp.mcp.pojo.dto.AuthDTO;
import com.rfsp.mcp.pojo.dto.FinancePDFDTO;
import com.rfsp.common.pojo.po.OrgPO;
import com.rfsp.mcp.pojo.po.PunishPO;

import cfca.com.itextpdf.text.pdf.PdfEncodings;
import cfca.com.itextpdf.text.pdf.PdfFont;
import cfca.sadk.com.itextpdf.kernel.font.PdfFontFactory;

import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;

/**
 * 给PDF 加水印功能（文字水印和图片水印）
 * 
 * @author yangxp
 */
public class McpPdfUtil {
	private static final Logger logger = LoggerFactory.getLogger(McpPdfUtil.class);
	
	/** 定义页面中央标题文字的字体 */
    public static Font font4DocTitle;

	/** 定义页面中某些标题文字的字体 */
    public static Font font4Title;

	/** 定义页面中某些侧边的字体 */
	public static Font font4SecValue;

	/** 定义页面关键字/值配对中关键字文字的字体 */
    public static Font font4Name;
    public static Font font5Name;

	/** 定义页面关键字/值配对中关键字文字的加粗字体 */
    public static Font font4NameBold;
    public static Font font5NameBold;

	/** 定义页面关键字/值配对中值文字的字体 */
    public static Font font4Value;

	/** 定义页面关键字/值配对中值文字的加粗字体 */
    public static Font font4ValueBold;

	/** 定义空行文字的字体 */
    public static Font font4SpaceLine;

	/** 定义页眉文字的字体 */
    public static Font font4PageTop;

	/** 定义页脚文字的字体 */
    public static Font font4PageBottom;

    public static Color titleBgColor;

	static {
		BaseFont bfComic;
		try {
			bfComic = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
			font4DocTitle = new Font(bfComic, 16, Font.BOLD);
			font4Title = new Font(bfComic, 14, Font.BOLD);
			font4SecValue = new Font(bfComic, 13, Font.BOLD);
			font4Name = new Font(bfComic, 12, Font.NORMAL);
			font5Name = new Font(bfComic, 10, Font.NORMAL);
			font4NameBold = new Font(bfComic, 12, Font.BOLD);
			font5NameBold = new Font(bfComic, 10, Font.BOLD);
			font4Value = new Font(bfComic, 10, Font.NORMAL);
			font4ValueBold = new Font(bfComic, 10, Font.BOLD);
			font4SpaceLine = new Font(bfComic, 4, Font.NORMAL);
			font4PageTop = new Font(bfComic, 8, Font.NORMAL);
			font4PageBottom = new Font(bfComic, 8, Font.NORMAL);

			titleBgColor = new Color(200, 200, 200);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 创建融资申请PDF
	 * @param dirPath 输出文件路径
	 * @return 融资申请pdf全路径
	 * @throws Exception
	 */
	public static String buildMiInfoPDF(Map<String,Object> map, String dirPath) throws Exception {
		File f = new File(dirPath);
		if((!f.exists())||(!f.isDirectory())){
			f.mkdirs();
		}
		
		OrgPO currentOrg = ShiroUtils.getCurrentOrg();
		
		String pdfPath = dirPath + currentOrg.getOrgCode() + ".pdf";
		String pdfPathTemp = dirPath + currentOrg.getOrgCode() + "_temp.pdf";
		
		File pdf = new File(pdfPathTemp);  // 定义PDF 生成文件(主要是路径)
		
		Document doc = new Document();
		PdfWriter.getInstance(doc,new FileOutputStream(pdf));	
		doc.setPageSize(PageSize.A4);
		doc.setMargins(30, 30, 30, 30);
		
		try {
			doc.open();
			Paragraph paragraph = new Paragraph();
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph.add(Chunk.NEWLINE);
			paragraph.add(Chunk.NEWLINE);
			Anchor link = new Anchor("主体信息汇总表", font4DocTitle);
			link.setName("link");
			paragraph.add(link);
			doc.add(paragraph);
			
			paragraph = new Paragraph("生成时间："+String.valueOf(map.get("date")), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("注册基本信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			
			
			int[] colWidth = new int[]{15,15,15,15};
			String[] colNames = new String[]{"机构名称", "统一社会信用代码", "法定代表人/负责人姓名", "企业类型"};
			String[] datas = new String[]{XssUtils.replaceUnXssAll(String.valueOf(map.get("orgName"))), String.valueOf(map.get("orgCode")), String.valueOf(map.get("corporation")), String.valueOf(map.get("enterpriseType"))};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			colWidth = new int[]{60};
			colNames = new String[]{"住所"};
			datas = new String[]{String.valueOf(map.get("orgAddress"))};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			paragraph = new Paragraph("政务共享信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(20);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			
			colWidth = new int[]{30,30};
			colNames = new String[]{"信息来源", "更新时间"};
			datas = new String[]{String.valueOf(map.get("ybjSource")), String.valueOf(map.get("ybjDate"))};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			colWidth = new int[]{15,15,15,15};
			colNames = new String[]{"医疗机构代码", "法定代表人", "地址", "经营性质"};
			datas = new String[]{String.valueOf(map.get("orgNo")), String.valueOf(map.get("comName")), String.valueOf(map.get("ybjAddress")), String.valueOf(map.get("bizNature"))};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			colWidth = new int[]{15,15,15,15};
			colNames = new String[]{"医保区划", "医疗机构类别", "医院等级", "主要负责人"};
//			datas = new String[]{McpConst.YbjBizAreaDict.getVal(String.valueOf(map.get("bizArea"))), McpConst.YbjOrgTypeDict.getVal(String.valueOf(map.get("orgType"))), McpConst.YbjOrgClassDict.getVal(String.valueOf(map.get("orgClass"))), String.valueOf(map.get("director"))};
			datas = new String[]{String.valueOf(map.get("bizArea")), String.valueOf(map.get("orgType")), String.valueOf(map.get("orgClass")), String.valueOf(map.get("director"))};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			
			
			
			colWidth = new int[]{30,30};
			colNames = new String[]{"银行账号", "开户银行"};
			datas = new String[]{String.valueOf(map.get("accountNo")), String.valueOf(map.get("accountBank"))};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			
			if("1".equals(String.valueOf(map.get("wjwDataFlag")))) {
				paragraph = new Paragraph("", font4NameBold);
				paragraph.setAlignment(Paragraph.ALIGN_CENTER);
				paragraph.add(Chunk.NEWLINE);
				paragraph.setSpacingAfter(5);
				doc.add(paragraph);
				
				colWidth = new int[]{15,15};
				colNames = new String[]{"信息来源", "更新时间"};
				datas = new String[]{String.valueOf(map.get("wjwSource")), String.valueOf(map.get("wjwDate"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
				
				colWidth = new int[]{15,15,15,15};
				colNames = new String[]{"当前状态", "批准日期", "批准文号", "行政区划"};
				datas = new String[]{String.valueOf(map.get("orgStatus")), String.valueOf(map.get("verifyDate")), String.valueOf(map.get("verifyFileNo")), String.valueOf(map.get("wjwBizArea"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
				
				colWidth = new int[]{15,15,15,15};
				colNames = new String[]{"有效期开始日期", "有效期截止日期", "下一校验日期", "登记发证机关"};
				datas = new String[]{String.valueOf(map.get("validityBeginDate")), String.valueOf(map.get("validityEndDate")), String.valueOf(map.get("nextCheckDate")), String.valueOf(map.get("regAgency"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
				
				colWidth = new int[]{15,15,15,15};
				colNames = new String[]{"机构类别", "机构级别", "机构等次", "经营性质"};
				datas = new String[]{String.valueOf(map.get("orgCategory")), String.valueOf(map.get("wjwOrgClass")), String.valueOf(map.get("orgGrade")), String.valueOf(map.get("bizType"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
				
				colWidth = new int[]{15,15,30};
				colNames = new String[]{"床位数", "牙椅数", "服务方式"};
				datas = new String[]{String.valueOf(map.get("bedSize")), String.valueOf(map.get("chairSize")), String.valueOf(map.get("serviceMode"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
				
				colWidth = new int[]{15,45};
				datas = new String[]{"诊疗科目名称", String.valueOf(map.get("bizSubject"))};
				doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			}
			
			
			if("1".equals(String.valueOf(map.get("sjjDataFlag")))) {
				paragraph = new Paragraph("", font4NameBold);
				paragraph.setAlignment(Paragraph.ALIGN_CENTER);
				paragraph.add(Chunk.NEWLINE);
				paragraph.setSpacingAfter(5);
				doc.add(paragraph);
				
				
				
				colWidth = new int[]{30,30};
				colNames = new String[]{"数据来源", "更新时间"};
				datas = new String[]{String.valueOf(map.get("sjjSource")), String.valueOf(map.get("sjjDate"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
				
				colWidth = new int[]{15,15,15,15};
				colNames = new String[]{"股东信息", "经营范围", "登记状态", "经营方式"};
				datas = new String[]{String.valueOf(map.get("stockHolder")), String.valueOf(map.get("bizScope")), String.valueOf(map.get("regStatus")), String.valueOf(map.get("bizOper"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
				
				colWidth = new int[]{15,15};
				colNames = new String[]{"联系信息", "经营场所"};
				datas = new String[]{String.valueOf(map.get("contactMobile")), String.valueOf(map.get("bizPlace"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			}
			
			
			
			if("1".equals(String.valueOf(map.get("punishDataFlag")))) {
				List<PunishPO> punishList = (List<PunishPO>) map.get("punishList");
				
				for(PunishPO punishPO:punishList) {
					
					Map<String,Object> punishMap = new HashMap<String,Object>();
					try {
						punishMap = JsonUtil.toMap(JsonUtil.toJson(punishPO));
						punishMap = XssUtils.replaceUnXss(punishMap);
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					paragraph = new Paragraph("", font4NameBold);
					paragraph.setAlignment(Paragraph.ALIGN_CENTER);
					paragraph.add(Chunk.NEWLINE);
					paragraph.setSpacingAfter(5);
					doc.add(paragraph);
					
					colWidth = new int[]{15,45};
					datas = new String[]{"行政相对人名称", String.valueOf(punishMap.get("orgName"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
					
					colWidth = new int[]{15,45};
					datas = new String[]{"行政处罚决定书文", String.valueOf(punishMap.get("documentNo"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
					
					colWidth = new int[]{15,45};
					datas = new String[]{"违法行为类型", String.valueOf(punishMap.get("errorType"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
					
					colWidth = new int[]{15,45};
					datas = new String[]{"违法事实", String.valueOf(punishMap.get("errorInfo"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
					
					colWidth = new int[]{15,45};
					datas = new String[]{"处罚类别", String.valueOf(punishMap.get("punishType"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
					
					colWidth = new int[]{15,45};
					datas = new String[]{"处罚内容", String.valueOf(punishMap.get("punishInfo"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
					
					colWidth = new int[]{15,45};
					datas = new String[]{"罚款金额", String.valueOf(punishMap.get("punishAmount"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
					
					colWidth = new int[]{15,45};
					datas = new String[]{"暂扣或吊销证照名称及编号", String.valueOf(punishMap.get("revokeOrgInfo"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
					
					colWidth = new int[]{15,45};
					datas = new String[]{"处罚决定日期", String.valueOf(punishMap.get("punishStartDate"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
					
					colWidth = new int[]{15,45};
					datas = new String[]{"处罚有效期", String.valueOf(punishMap.get("punishEndDate"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
					
					colWidth = new int[]{15,45};
					datas = new String[]{"处罚机关", String.valueOf(punishMap.get("punishDept"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
				}
			}
			
			
			if((map.get("fill_55") != null) && (StringUtils.isNotBlank(String.valueOf(map.get("fill_55"))))) {
				paragraph = new Paragraph("以下信息由医保定点机构填写", font4NameBold);
				paragraph.setAlignment(Paragraph.ALIGN_LEFT);
				paragraph.add(Chunk.NEWLINE);
				paragraph.setSpacingBefore(15);
				paragraph.setSpacingAfter(5);
				doc.add(paragraph);
				
				colWidth = new int[]{15,45};
				datas = new String[]{"备注", String.valueOf(map.get("fill_55"))};
				doc.add(writerTable(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			}
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (doc != null) {
				doc.close();
			}
		}
		

		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pdfPath));
        setWatermark(bos, pdfPathTemp);
		
		bos.close();
		File ff = new File(pdfPathTemp);
		if(ff.exists()) {
			ff.delete();
		}
		
		return pdfPath;
	}

	/**
	 * 创建主体信息汇总表PDF-医保贷
	 * @param dirPath 输出文件路径
	 * @return 主体信息汇总表PDF全路径
	 * @throws Exception
	 */
	public static String buildMiInfoYBDPDF(Map<String,Object> map, String dirPath) throws Exception {
		File f = new File(dirPath);
		if((!f.exists())||(!f.isDirectory())){
			f.mkdirs();
		}

		OrgPO currentOrg = ShiroUtils.getCurrentOrg();

		String pdfPath = dirPath + currentOrg.getOrgCode() + ".pdf";
		String pdfPathTemp = dirPath + currentOrg.getOrgCode() + "_temp.pdf";

		File outputFile = new File(pdfPathTemp);  // 定义PDF 生成文件(主要是路径)
		// 确保目录存在
		File parentDir = outputFile.getParentFile();
		if (parentDir != null && !parentDir.exists()) {
			Files.createDirectories(parentDir.toPath());
		}
		FileOutputStream fileOutputStream = null;
		Document doc = null;
		try {
			doc = new Document();
			doc.setPageSize(PageSize.A4);
			doc.setMargins(30, 30, 30, 30);
			fileOutputStream = new FileOutputStream(outputFile);
			PdfWriter.getInstance(doc,fileOutputStream);
			doc.open();
			Paragraph paragraph = new Paragraph();
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph.add(Chunk.NEWLINE);
			paragraph.add(Chunk.NEWLINE);
			Anchor link = new Anchor("主体信息汇总表", font4DocTitle);
			link.setName("link");
			paragraph.add(link);
			doc.add(paragraph);

			paragraph = new Paragraph("查询时间：" + String.valueOf(map.get("date")), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
//			logger.info(JsonUtil.toJson(map));
			doc.add(writerPlantformReg(map));
			doc.add(writerShareInfo(map));
		}catch (Exception e){
			e.printStackTrace();
		} finally {
			// 正确关闭顺序:
			// 1. 先关闭Document (这会完成PDF写入并关闭PdfWriter)
			if (doc != null && doc.isOpen()) {
				doc.close(); // 重要：这会自动关闭PdfWriter和底层流
			}

			// 2. 不要再单独关闭FileOutputStream!
			// 因为doc.close()已经关闭了它

			// 3. 特别情况处理：如果doc关闭失败，再关闭流
			if (fileOutputStream != null) {
				if (doc == null || !doc.isOpen()) {
					fileOutputStream.close();
				}
			}
		}
		try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pdfPath))) {
            setWatermark(bos, pdfPathTemp);
		} catch (Exception e) {
			e.printStackTrace();
		}

		File ff = new File(pdfPathTemp);
		if(ff.exists()) {
			ff.delete();
		}

		return pdfPath;
	}

	/**
	 * 生成主体汇总表到本地服务
	 * @param map
	 * @param fileName
	 * @param filePath
	 * @throws Exception
	 */
	public static void buildMainInfoPDF(Map<String,Object> map, String fileName, String filePath) throws Exception {
		// 2. 直接通过 response 的输出流构建 PdfWriter
		Document doc = null;
		FileOutputStream fileOutputStream = null;
		PdfWriter pdfWriter = null;
		FileUtil.createDirectory(filePath);
		// 3. 填充内容（示例）
		try{
			fileOutputStream = new FileOutputStream(Paths.get(filePath + fileName).toFile());
			doc = new Document();
			doc.setPageSize(PageSize.A4);
			doc.setMargins(30, 30, 30, 30);
			pdfWriter = PdfWriter.getInstance(doc, fileOutputStream);
			doc.open();
			Paragraph paragraph = new Paragraph();
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph.add(Chunk.NEWLINE);
			paragraph.add(Chunk.NEWLINE);
			Anchor link = new Anchor("主体信息汇总表", font4DocTitle);
			link.setName("link");
			paragraph.add(link);
			doc.add(paragraph);

			paragraph = new Paragraph("查询时间：" + String.valueOf(map.get("date")), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			doc.add(writerPlantformRegForPayLog(map));
			doc.add(writerShareInfoForPayLog(map));

			//添加水印
			// 从类路径加载水印图片（放在resources/images/watermark.png）
			// 从类路径加载图片（路径：src/main/resources/images/watermark.png）
			ClassPathResource imageResource = new ClassPathResource("mcp/images/waterMarkA4.jpg");
			Image image = Image.getInstance(imageResource.getURL());
			float X = pdfWriter.getPageSize().getWidth();
			float Y = pdfWriter.getPageSize().getHeight();
			image.scalePercent(50.8f);
			image.setAbsolutePosition(0, 0);
			image.setRotationDegrees(0);// 旋转
			image.setAbsolutePosition(0, 0);
			image.scaleAbsolute(X, Y);

			pdfWriter.setPageEvent(new ImageWatermark(image));
			fileOutputStream.flush();
		} catch (Exception e) {
			logger.error("创建主体文件异常,{}", e);
		}finally {
			// 正确关闭顺序:
			// 1. 先关闭Document (这会完成PDF写入并关闭PdfWriter)
			if (doc != null && doc.isOpen()) {
				doc.close(); // 重要：这会自动关闭PdfWriter和底层流
			}

			// 2. 不要再单独关闭FileOutputStream!
			// 因为doc.close()已经关闭了它
			if (pdfWriter != null) {
				if (doc == null || !doc.isOpen()) {
					pdfWriter.close();
				}
			}
			// 3. 特别情况处理：如果doc关闭失败，再关闭流
			if (fileOutputStream != null) {
				if (doc == null || !doc.isOpen()) {
					fileOutputStream.close();
				}
			}
		}
	}

	private static PdfPTable writerShareInfoForPayLog(Map dataMap) throws Exception {
		int[] colWidth = new int[]{15,30,30,30,15,15,15};
		PdfPTable pdfPTable = new PdfPTable(colWidth.length);
		pdfPTable.setWidths(colWidth);
		pdfPTable.setWidthPercentage(100);
		pdfPTable.setSpacingBefore(0);

		PDFPCell colTitle = new PDFPCell(new Paragraph("政务共享信息", font4SecValue));
		colTitle.setRowspan(15);
		pdfPTable.addCell(colTitle);

		pdfPTable.addCell(new PDFPCell(new Paragraph("信息来源", font4ValueBold)));
		PDFPCell source =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("source")), font4Value));
		source.setColspan(5);
		pdfPTable.addCell(source);
		PDFPCell title1 =new PDFPCell(new Paragraph("一、基本信息", font4ValueBold));
		title1.setColspan(6);
		pdfPTable.addCell(title1);

		pdfPTable.addCell(new PDFPCell(new Paragraph("医保定点机构名称", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("orgNameYbj")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("统一社会信用代码", font4ValueBold)));
		PDFPCell creditCode =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("orgCodeYbj")), font4Value));
		creditCode.setColspan(3);
		pdfPTable.addCell(creditCode);

		pdfPTable.addCell(new PDFPCell(new Paragraph("医保定点机构代码", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("orgNo")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("法定代表人", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("comName")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("主要负责人", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("director")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("地址", font4ValueBold)));
		PDFPCell addr =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("ybjAddress")), font4Value));
		addr.setColspan(5);
		pdfPTable.addCell(addr);

		pdfPTable.addCell(new PDFPCell(new Paragraph("经济类型", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("economicType")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("经营性质", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("bizNature")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("隶属关系", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("affiliation")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("医疗机构类别", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("orgType")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("床位数", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("bedNum")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("医院等级", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("orgClass")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("收费等级", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("feeLevel")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("医院等次", font4ValueBold)));
		PDFPCell hoslevel =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("orgGrade")), font4Value));
		hoslevel.setColspan(3);
		pdfPTable.addCell(hoslevel);

		pdfPTable.addCell(new PDFPCell(new Paragraph("诊疗科目", font4ValueBold)));
		PDFPCell zhenliaokemu =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("bizSubject")), font4Value));
		zhenliaokemu.setColspan(5);
		pdfPTable.addCell(zhenliaokemu);

		pdfPTable.addCell(new PDFPCell(new Paragraph("执业许可证号", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("proLicenseNo")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("执业许可有效期限", font4ValueBold)));
		PDFPCell licence =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("prolicNoTimeLimit")), font4Value));
		licence.setColspan(3);
		pdfPTable.addCell(licence);

		PDFPCell title2 =new PDFPCell(new Paragraph("二、医保服务协议信息", font4ValueBold));
		title2.setColspan(6);
		pdfPTable.addCell(title2);

		pdfPTable.addCell(new PDFPCell(new Paragraph("批准建档时间", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("approveTime")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("批准文号", font4ValueBold)));
		PDFPCell wenhao =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("approveNo")), font4Value));
		wenhao.setColspan(3);
		pdfPTable.addCell(wenhao);

		pdfPTable.addCell(new PDFPCell(new Paragraph("定点机构有效性", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("validFlag")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("医保区划", font4ValueBold)));
		PDFPCell area =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("bizArea")), font4Value));
		area.setColspan(3);
		pdfPTable.addCell(area);

		pdfPTable.addCell(new PDFPCell(new Paragraph("医保服务协议有效期开始日期", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("validStartDate")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("医保服务协议有效期截止日期", font4ValueBold)));
		PDFPCell enddate =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("validEndDate")), font4Value));
		enddate.setColspan(3);
		pdfPTable.addCell(enddate);

		pdfPTable.addCell(new PDFPCell(new Paragraph("医保评级", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("miGrade")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("结算支持类型", font4ValueBold)));
		PDFPCell supportType =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("payType")), font4Value));
		supportType.setColspan(3);
		pdfPTable.addCell(supportType);

		return pdfPTable;
	}

	/**
	 * 从本地服务读取文件通过response返回到前端
	 * @param response
	 * @param filePath
	 * @param fileName
	 * @param deleteFile
	 * @throws Exception
	 */
	public static void responseMainInfoPDF(HttpServletResponse response, String filePath, String fileName, boolean deleteFile) throws Exception {
		// 1. 设置响应头 —— attachment 表示下载
		response.setContentType("application/pdf");
		String encoded = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
		response.setHeader("Content-Disposition",
				"attachment; filename=\"" + encoded + "\";" +
						"filename*=utf-8''" + encoded);
		Path path = Paths.get(filePath + fileName);
		BufferedInputStream bis = null;
		OutputStream os = null;
		try (InputStream fis = Files.newInputStream(path)) {
			bis = new BufferedInputStream(fis);
			os = response.getOutputStream();
			// 3. 使用缓冲区高效传输（8KB缓冲区）
			byte[] buffer = new byte[8192];
			int bytesRead;
			while ((bytesRead = bis.read(buffer)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.flush();
			if (deleteFile) {
				Files.deleteIfExists(path);
			}
		} catch (NoSuchFileException e) {
			// 4. 处理文件不存在异常
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			logger.error("创建主体文件异常,{}", e);
		} catch (IOException e) {
			// 处理其他IO异常
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			logger.error("创建主体文件异常,{}", e);
		}finally {
			if (bis != null) {
				bis.close();
			}
			if (os != null && !response.isCommitted()) {
				try {
					os.close(); // 仅在响应未提交时关闭
				} catch (IOException e) {
					logger.error("创建主体文件异常,{}", e);
				}
			}
		}
	}
	
	/**
	 * 创建融资申请PDF
	 * @param financePDFDTO
	 * @param dirPath 输出文件路径
	 * @return 融资申请pdf全路径
	 * @throws Exception
	 */
	public static String buildFinanceAndMiInfoPDF(FinancePDFDTO financePDFDTO, Map<String,Object> map, String dirPath) throws Exception {
		File f = new File(dirPath);
		if((!f.exists())||(!f.isDirectory())){
			f.mkdirs();
		}
		
		String pdfPath = dirPath + financePDFDTO.getFinanceNo() + ".pdf";
		String pdfPathTemp = dirPath + financePDFDTO.getFinanceNo() + "_temp.pdf";
		
		File pdf = new File(pdfPathTemp);  // 定义PDF 生成文件(主要是路径)
		
		Document doc = new Document();
		PdfWriter.getInstance(doc,new FileOutputStream(pdf));	
		doc.setPageSize(PageSize.A4);
		doc.setMargins(30, 30, 30, 30);
		
		
		try {
			doc.open();
			   
			Paragraph paragraph = new Paragraph("中征平台医惠贷业务融资申请表", font4DocTitle);
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph .add(Chunk.NEWLINE);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("编号："+financePDFDTO.getFinanceNo(), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("融资主体信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			
			
			
			//String href = "http://127.0.0.1:7013/mcp/hos/hospital/miDetail/?miNo="+financePDFDTO.getMiNo();
			int[] colWidth = new int[]{15,15,15,15};
			String[] colNames = new String[]{"名称", "统一社会信用代码", "注册地址", "主体信息汇总表"};
			String[] datas = new String[]{financePDFDTO.getMiOrgName(), financePDFDTO.getMiOrgCode(), financePDFDTO.getMiRegAdr(), financePDFDTO.getMiNo()};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			
			paragraph = new Paragraph("融资申请信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"医保统筹区", "定点机构类型", "借款用途"};
			datas = new String[]{financePDFDTO.getAreaName(), financePDFDTO.getMiOrgType(), XssUtils.replaceUnXssAll(financePDFDTO.getFinancePurpose())};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"币种", "融资申请金额", "融资申请期限"};
			datas = new String[]{"人民币元", DecimalUtil.format3(financePDFDTO.getFinanceAmount()), financePDFDTO.getFinanceLimit()};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			
			paragraph = new Paragraph("医保结算账户信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"开户名称", "银行账号", "开户行"};
			datas = new String[]{XssUtils.replaceUnXssAll(financePDFDTO.getAccountName()), XssUtils.replaceUnXssAll(financePDFDTO.getAccountNo()), XssUtils.replaceUnXssAll(financePDFDTO.getAccountBank())};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			
			paragraph = new Paragraph("授权书信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"授权书编号", "授权起始时间", "授权终止时间"};
			datas = new String[]{financePDFDTO.getAuthNo(), financePDFDTO.getAuthStartTime(), financePDFDTO.getAuthEndTime()};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			
			paragraph = new Paragraph("联系信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"联系人", "移动电话", "固定电话"};
			datas = new String[]{XssUtils.replaceUnXssAll(financePDFDTO.getContactName()), financePDFDTO.getContactMobile(), XssUtils.replaceUnXssAll(financePDFDTO.getContactTel())};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			
			paragraph = new Paragraph("备注", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{60};
			datas = new String[]{XssUtils.replaceUnXssAll(financePDFDTO.getFinanceRemark())};
			doc.add(writerTable(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_LEFT));
			
			
			paragraph = new Paragraph("业务规则", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setSpacingBefore(15);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("■我知悉并同意授权资金方通过中征应收账款融资服务平台查询我方主体信息、医保结算信息等。", font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("■我已认真阅读并同意《中征医惠贷业务规则》。", font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingAfter(10);
			doc.add(paragraph);
			
			paragraph = new Paragraph("机构名称：" + financePDFDTO.getMiOrgName(), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("申请日期：" + financePDFDTO.getApplyTime(), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			
			
			doc.newPage();


			paragraph = new Paragraph();
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph.add(Chunk.NEWLINE);
			paragraph.add(Chunk.NEWLINE);
			Anchor link = new Anchor("主体信息汇总表", font4DocTitle);
			link.setName("link");
			paragraph.add(link);
			doc.add(paragraph);

			paragraph = new Paragraph("查询时间："+String.valueOf(map.get("date")), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph("平台注册信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);


			colWidth = new int[]{15,15,15,15};
			colNames = new String[]{"机构名称", "统一社会信用代码", "法定代表人/负责人姓名", "企业类型"};
			datas = new String[]{XssUtils.replaceUnXssAll(String.valueOf(map.get("orgName"))), String.valueOf(map.get("orgCode")), String.valueOf(map.get("corporation")), String.valueOf(map.get("enterpriseType"))};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

			colWidth = new int[]{60};
			colNames = new String[]{"住所"};
			datas = new String[]{String.valueOf(map.get("orgAddress"))};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

			paragraph = new Paragraph("政务共享信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(20);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);

			colWidth = new int[]{30,30};
			colNames = new String[]{"信息来源", "更新时间"};
			datas = new String[]{String.valueOf(map.get("ybjSource")), String.valueOf(map.get("ybjDate"))};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

			colWidth = new int[]{15,15,15,15};
			colNames = new String[]{"医疗机构代码", "法定代表人", "地址", "经营性质"};
			datas = new String[]{String.valueOf(map.get("orgNo")), String.valueOf(map.get("comName")), String.valueOf(map.get("ybjAddress")), String.valueOf(map.get("bizNature"))};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

			colWidth = new int[]{15,15,15,15};
			colNames = new String[]{"医保区划", "医疗机构类别", "医院等级", "主要负责人"};
//			datas = new String[]{McpConst.YbjBizAreaDict.getVal(String.valueOf(map.get("bizArea"))), McpConst.YbjOrgTypeDict.getVal(String.valueOf(map.get("orgType"))), McpConst.YbjOrgClassDict.getVal(String.valueOf(map.get("orgClass"))), String.valueOf(map.get("director"))};
			datas = new String[]{String.valueOf(map.get("bizArea")), String.valueOf(map.get("orgType")), String.valueOf(map.get("orgClass")), String.valueOf(map.get("director"))};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

			colWidth = new int[]{30,30};
			colNames = new String[]{"银行账号", "开户银行"};
			datas = new String[]{String.valueOf(map.get("accountNo")), String.valueOf(map.get("accountBank"))};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));




			if("1".equals(String.valueOf(map.get("wjwDataFlag")))) {
				paragraph = new Paragraph("", font4NameBold);
				paragraph.setAlignment(Paragraph.ALIGN_CENTER);
				paragraph.add(Chunk.NEWLINE);
				paragraph.setSpacingAfter(5);
				doc.add(paragraph);

				colWidth = new int[]{15,15};
				colNames = new String[]{"信息来源", "更新时间"};
				datas = new String[]{String.valueOf(map.get("wjwSource")), String.valueOf(map.get("wjwDate"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

				colWidth = new int[]{15,15,15,15};
				colNames = new String[]{"当前状态", "批准日期", "批准文号", "行政区划"};
				datas = new String[]{String.valueOf(map.get("orgStatus")), String.valueOf(map.get("verifyDate")), String.valueOf(map.get("verifyFileNo")), String.valueOf(map.get("wjwBizArea"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

				colWidth = new int[]{15,15,15,15};
				colNames = new String[]{"有效期开始日期", "有效期截止日期", "下一校验日期", "登记发证机关"};
				datas = new String[]{String.valueOf(map.get("validityBeginDate")), String.valueOf(map.get("validityEndDate")), String.valueOf(map.get("nextCheckDate")), String.valueOf(map.get("regAgency"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

				colWidth = new int[]{15,15,15,15};
				colNames = new String[]{"机构类别", "机构级别", "机构等次", "经营性质"};
				datas = new String[]{String.valueOf(map.get("orgCategory")), String.valueOf(map.get("wjwOrgClass")), String.valueOf(map.get("orgGrade")), String.valueOf(map.get("bizType"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

				colWidth = new int[]{15,15,30};
				colNames = new String[]{"床位数", "牙椅数", "服务方式"};
				datas = new String[]{String.valueOf(map.get("bedSize")), String.valueOf(map.get("chairSize")), String.valueOf(map.get("serviceMode"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

				colWidth = new int[]{15,45};
				colNames = null;
				datas = new String[]{"诊疗科目名称", String.valueOf(map.get("bizSubject"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			}


			if("1".equals(String.valueOf(map.get("sjjDataFlag")))) {
				paragraph = new Paragraph("", font4NameBold);
				paragraph.setAlignment(Paragraph.ALIGN_CENTER);
				paragraph.add(Chunk.NEWLINE);
				paragraph.setSpacingAfter(5);
				doc.add(paragraph);



				colWidth = new int[]{30,30};
				colNames = new String[]{"数据来源", "更新时间"};
				datas = new String[]{String.valueOf(map.get("sjjSource")), String.valueOf(map.get("sjjDate"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

				colWidth = new int[]{15,15,15,15};
				colNames = new String[]{"股东信息", "经营范围", "登记状态", "经营方式"};
				datas = new String[]{String.valueOf(map.get("stockHolder")), String.valueOf(map.get("bizScope")), String.valueOf(map.get("regStatus")), String.valueOf(map.get("bizOper"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

				colWidth = new int[]{15,15};
				colNames = new String[]{"联系信息", "经营场所"};
				datas = new String[]{String.valueOf(map.get("contactMobile")), String.valueOf(map.get("bizPlace"))};
				doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			}



			if("1".equals(String.valueOf(map.get("punishDataFlag")))) {
				List<PunishPO> punishList = (List<PunishPO>) map.get("punishList");

				for(PunishPO punishPO:punishList) {

					Map<String,Object> punishMap = new HashMap<String,Object>();
					try {
						punishMap = JsonUtil.toMap(JsonUtil.toJson(punishPO));
						punishMap = XssUtils.replaceUnXss(punishMap);
					} catch (Exception e) {
						e.printStackTrace();
					}

					paragraph = new Paragraph("", font4NameBold);
					paragraph.setAlignment(Paragraph.ALIGN_CENTER);
					paragraph.add(Chunk.NEWLINE);
					paragraph.setSpacingAfter(5);
					doc.add(paragraph);

					colWidth = new int[]{15,45};
					datas = new String[]{"行政相对人名称", String.valueOf(punishMap.get("orgName"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

					colWidth = new int[]{15,45};
					datas = new String[]{"行政处罚决定书文", String.valueOf(punishMap.get("documentNo"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

					colWidth = new int[]{15,45};
					datas = new String[]{"违法行为类型", String.valueOf(punishMap.get("errorType"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

					colWidth = new int[]{15,45};
					datas = new String[]{"违法事实", String.valueOf(punishMap.get("errorInfo"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

					colWidth = new int[]{15,45};
					datas = new String[]{"处罚类别", String.valueOf(punishMap.get("punishType"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

					colWidth = new int[]{15,45};
					datas = new String[]{"处罚内容", String.valueOf(punishMap.get("punishInfo"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

					colWidth = new int[]{15,45};
					datas = new String[]{"罚款金额", String.valueOf(punishMap.get("punishAmount"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

					colWidth = new int[]{15,45};
					datas = new String[]{"暂扣或吊销证照名称及编号", String.valueOf(punishMap.get("revokeOrgInfo"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

					colWidth = new int[]{15,45};
					datas = new String[]{"处罚决定日期", String.valueOf(punishMap.get("punishStartDate"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

					colWidth = new int[]{15,45};
					datas = new String[]{"处罚有效期", String.valueOf(punishMap.get("punishEndDate"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

					colWidth = new int[]{15,45};
					datas = new String[]{"处罚机关", String.valueOf(punishMap.get("punishDept"))};
					doc.add(writerTableFor2Cell(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
				}
			}




			if((map.get("fill_55") != null) && (StringUtils.isNotBlank(String.valueOf(map.get("fill_55"))))) {
				paragraph = new Paragraph("以下信息由医保定点机构填写", font4NameBold);
				paragraph.setAlignment(Paragraph.ALIGN_LEFT);
				paragraph.add(Chunk.NEWLINE);
				paragraph.setSpacingBefore(15);
				paragraph.setSpacingAfter(5);
				doc.add(paragraph);
				
				colWidth = new int[]{15,45};
				datas = new String[]{"备注", String.valueOf(map.get("fill_55"))};
				doc.add(writerTable(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (doc != null) {
				doc.close();
			}
		}
		

		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pdfPath));
        setWatermark(bos, pdfPathTemp);
		
		bos.close();
		File ff = new File(pdfPathTemp);
		if(ff.exists()) {
			ff.delete();
		}
		
		return pdfPath;
	}

	/**
	 * 创建融资申请PDF
	 * @param financePDFDTO
	 * @param dirPath 输出文件路径
	 * @return 融资申请pdf全路径
	 * @throws Exception
	 */
	public static String buildFinanceAndMiInfoYBDPDF(FinancePDFDTO financePDFDTO, Map<String,Object> map, String dirPath) throws Exception {
		File f = new File(dirPath);
		if((!f.exists())||(!f.isDirectory())){
			f.mkdirs();
		}

		String pdfPath = dirPath + financePDFDTO.getFinanceNo() + ".pdf";
		String pdfPathTemp = dirPath + financePDFDTO.getFinanceNo() + "_temp.pdf";

		File pdf = new File(pdfPathTemp);  // 定义PDF 生成文件(主要是路径)

		Document doc = new Document();
		PdfWriter.getInstance(doc,new FileOutputStream(pdf));
		doc.setPageSize(PageSize.A4);
		doc.setMargins(30, 30, 30, 30);


		try {
			doc.open();

			Paragraph paragraph = new Paragraph("中征平台医保贷业务融资申请表", font4DocTitle);
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph .add(Chunk.NEWLINE);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph("编号："+financePDFDTO.getFinanceNo(), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph("融资主体信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);



			//String href = "http://127.0.0.1:7013/mcp/hos/hospital/miDetail/?miNo="+financePDFDTO.getMiNo();
			int[] colWidth = new int[]{15,15,15,15};
			String[] colNames = new String[]{"名称", "统一社会信用代码", "注册地址", "主体信息汇总表"};
			String[] datas = new String[]{financePDFDTO.getMiOrgName(), financePDFDTO.getMiOrgCode(), financePDFDTO.getMiRegAdr(), financePDFDTO.getMiNo()};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));


			paragraph = new Paragraph("融资申请信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"医保统筹区", "定点机构类型", "借款用途"};
			datas = new String[]{financePDFDTO.getAreaName(), financePDFDTO.getMiOrgType(), XssUtils.replaceUnXssAll(financePDFDTO.getFinancePurpose())};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));

			colWidth = new int[]{15,30,15};
			colNames = new String[]{"币种", "融资申请金额", "融资申请期限"};
			datas = new String[]{"人民币元", DecimalUtil.format3(financePDFDTO.getFinanceAmount()), financePDFDTO.getFinanceLimit()};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));


			paragraph = new Paragraph("医保结算账户信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"开户名称", "银行账号", "开户行"};
			datas = new String[]{XssUtils.replaceUnXssAll(financePDFDTO.getAccountName()), XssUtils.replaceUnXssAll(financePDFDTO.getAccountNo()), XssUtils.replaceUnXssAll(financePDFDTO.getAccountBank())};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));


			paragraph = new Paragraph("授权书信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"授权书编号", "授权起始时间", "授权终止时间"};
			datas = new String[]{financePDFDTO.getAuthNo(), financePDFDTO.getAuthStartTime(), financePDFDTO.getAuthEndTime()};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));


			paragraph = new Paragraph("联系信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"联系人", "移动电话", "固定电话"};
			datas = new String[]{XssUtils.replaceUnXssAll(financePDFDTO.getContactName()), financePDFDTO.getContactMobile(), XssUtils.replaceUnXssAll(financePDFDTO.getContactTel())};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));


			paragraph = new Paragraph("备注", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{60};
			datas = new String[]{XssUtils.replaceUnXssAll(financePDFDTO.getFinanceRemark())};
			doc.add(writerTable(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_LEFT));


			paragraph = new Paragraph("业务规则", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setSpacingBefore(15);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph("■我知悉并同意授权资金方通过中征应收账款融资服务平台查询我方主体信息、医保结算信息等。", font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph("■我已认真阅读并同意《中征应收账款融资服务平台医保贷业务规则》。", font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingAfter(10);
			doc.add(paragraph);

			paragraph = new Paragraph("机构名称：" + financePDFDTO.getMiOrgName(), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph("申请日期：" + financePDFDTO.getApplyTime(), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);



			doc.newPage();
			paragraph = new Paragraph();
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph.add(Chunk.NEWLINE);
			paragraph.add(Chunk.NEWLINE);
			Anchor link = new Anchor("主体信息汇总表", font4DocTitle);
			link.setName("link");
			paragraph.add(link);
			doc.add(paragraph);

			paragraph = new Paragraph("查询时间：" + String.valueOf(map.get("date")), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			logger.info(JsonUtil.toJson(map));
			doc.add(writerPlantformReg(map));
			doc.add(writerShareInfo(map));

			if((map.get("fill_55") != null) && (StringUtils.isNotBlank(String.valueOf(map.get("fill_55"))))) {
				paragraph = new Paragraph("以下信息由医保定点机构填写", font4NameBold);
				paragraph.setAlignment(Paragraph.ALIGN_LEFT);
				paragraph.add(Chunk.NEWLINE);
				paragraph.setSpacingBefore(15);
				paragraph.setSpacingAfter(5);
				doc.add(paragraph);

				colWidth = new int[]{15,45};
				datas = new String[]{"备注", String.valueOf(map.get("fill_55"))};
				doc.add(writerTable(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			}


		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (doc != null) {
				doc.close();
			}
		}


		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pdfPath));
        setWatermark(bos, pdfPathTemp);

		bos.close();
		File ff = new File(pdfPathTemp);
		if(ff.exists()) {
			ff.delete();
		}

		return pdfPath;
	}

	/**
	 * 创建融资申请PDF
	 * @param financePDFDTO
	 * @param dirPath
	 * @return 融资申请pdf全路径
	 * @throws Exception
	 */
	@Deprecated
	public static String buildFinancePDF(FinancePDFDTO financePDFDTO, String dirPath) throws Exception {
		File f = new File(dirPath);
		if((!f.exists())||(!f.isDirectory())){
			f.mkdirs();
		}
		
		
		String pdfPath = dirPath + financePDFDTO.getFinanceNo() + "_FI.pdf";
		String pdfPathTemp = dirPath + financePDFDTO.getFinanceNo() + "_temp.pdf";
		
		File pdf = new File(pdfPathTemp);  // 定义PDF 生成文件(主要是路径)
		
		Document doc = new Document();
		PdfWriter.getInstance(doc,new FileOutputStream(pdf));	
		doc.setPageSize(PageSize.A4);
		doc.setMargins(30, 30, 30, 30);
		
		
		try {
			doc.open();
			   
			Paragraph paragraph = new Paragraph("中征平台医惠贷业务融资申请表", font4DocTitle);
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph .add(Chunk.NEWLINE);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("编号："+financePDFDTO.getFinanceNo(), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("融资主体信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			
			
			
			//String href = "http://127.0.0.1:7013/mcp/hos/hospital/miDetail/?miNo="+financePDFDTO.getMiNo();
			int[] colWidth = new int[]{15,15,15,15};
			String[] colNames = new String[]{"名称", "统一社会信用代码", "注册地址", "主体信息汇总表"};
			String[] datas = new String[]{financePDFDTO.getMiOrgName(), financePDFDTO.getMiOrgCode(), financePDFDTO.getMiRegAdr(), financePDFDTO.getMiNo()};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			
			paragraph = new Paragraph("融资申请信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"医保统筹区", "定点机构类型", "借款用途"};
			datas = new String[]{financePDFDTO.getAreaName(), financePDFDTO.getMiOrgType(), financePDFDTO.getFinancePurpose()};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"币种", "融资申请金额", "融资申请期限"};
			datas = new String[]{"人民币元", financePDFDTO.getFinanceAmount(), financePDFDTO.getFinanceLimit()};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			
			paragraph = new Paragraph("医保结算账户信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"开户名称", "银行账号", "开户行"};
			datas = new String[]{financePDFDTO.getAccountName(), financePDFDTO.getAccountNo(), financePDFDTO.getAccountBank()};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			
			paragraph = new Paragraph("授权书信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"授权书编号", "授权起始时间", "授权终止时间"};
			datas = new String[]{financePDFDTO.getAuthNo(), financePDFDTO.getAuthStartTime(), financePDFDTO.getAuthEndTime()};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			
			paragraph = new Paragraph("联系信息", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{15,30,15};
			colNames = new String[]{"联系人", "移动电话", "固定电话"};
			datas = new String[]{financePDFDTO.getContactName(), financePDFDTO.getContactMobile(), financePDFDTO.getContactTel()};
			doc.add(writerTable(colWidth, colNames, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_CENTER));
			
			
			paragraph = new Paragraph("备注", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingBefore(15);
			paragraph.setSpacingAfter(5);
			doc.add(paragraph);
			colWidth = new int[]{60};
			datas = new String[]{financePDFDTO.getFinanceRemark()};
			doc.add(writerTable(colWidth, null, datas, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_LEFT));
			
			
			paragraph = new Paragraph("业务规则", font4NameBold);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setSpacingBefore(15);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("■我知悉并同意授权资金方通过中征应收账款融资服务平台查询我方政务信息、医保结算信息等。", font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("■我已认真阅读并同意《中征医惠贷业务规则》。", font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.setSpacingAfter(180);
			doc.add(paragraph);
			
			paragraph = new Paragraph("机构名称：" + financePDFDTO.getMiOrgName(), font4Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph();
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			Anchor link = new Anchor("申请日期：" + financePDFDTO.getApplyTime(), font4Value);
			link.setName("link");
			paragraph.add(link);
			doc.add(paragraph);
			
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (doc != null) {
				doc.close();
			}
		}
		

		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pdfPath));
        setWatermark(bos, pdfPathTemp);
		
		bos.close();
		File ff = new File(pdfPathTemp);
		if(ff.exists()) {
			ff.delete();
		}
		
		return pdfPath;
	}


	
	/**
	 * 第一列加粗，其他常规
	 * @param colWidth
	 * @param colNames
	 * @param datas
	 * @param colNamesAlignment
	 * @param colDataAlignment
	 * @return
	 * @throws Exception
	 */
	private static PdfPTable writerTableFor2Cell(int[] colWidth, String[] colNames, String[] datas, int colNamesAlignment, int colDataAlignment) throws Exception {
		PdfPTable pdfPTable = new PdfPTable(colWidth.length);
		pdfPTable.setWidths(colWidth);
		pdfPTable.setWidthPercentage(100);
		pdfPTable.setSpacingBefore(0);
		
		PDFPCell accountcell = null;
		
		boolean linkFlag = false;
		
		if(colNames != null) {
			for(String title:colNames) {
				if("主体信息汇总表".equals(title)) {linkFlag = true;}
				accountcell = new PDFPCell(new Paragraph(title, font4ValueBold));
				accountcell.setHorizontalAlignment(colNamesAlignment);		
				pdfPTable.addCell(accountcell);
			}
		}
		
		if(datas != null) {
			for(int i=0;i<datas.length;i++) {
				String data = datas[i];
				if("null".equals(datas[i]) || StringUtils.isBlank(datas[i])) {
					data = " ";
				}
				
				Paragraph paragraph = new Paragraph();
				if(i==0) {
					paragraph = new Paragraph(data, font4ValueBold);
				}else {
					paragraph = new Paragraph(data, font4Value);
				}
				
				accountcell = new PDFPCell(paragraph);
				accountcell.setHorizontalAlignment(colDataAlignment);		
				pdfPTable.addCell(accountcell);
			}
		}
		
		return pdfPTable;
	}


	private static PdfPTable writerPlantformReg(Map dataMap) throws Exception {
		int[] colWidth = new int[]{15,30,30,30,15,15,15};
		PdfPTable pdfPTable = new PdfPTable(colWidth.length);
		pdfPTable.setWidths(colWidth);
		pdfPTable.setWidthPercentage(100);
		pdfPTable.setSpacingBefore(0);

		PDFPCell colTitle = new PDFPCell(new Paragraph("平台注册信息", font4SecValue));
		colTitle.setRowspan(3);
		pdfPTable.addCell(colTitle);

		pdfPTable.addCell(new PDFPCell(new Paragraph("机构名称", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) dataMap.get("orgName"), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("统一社会信用代码", font4ValueBold)));
		PDFPCell creditCode =new PDFPCell(new Paragraph((String) dataMap.get("orgCode"), font4Value));
		creditCode.setColspan(3);
		pdfPTable.addCell(creditCode);

		pdfPTable.addCell(new PDFPCell(new Paragraph("法定代表人/负责人姓名", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) dataMap.get("corporation"), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("企业类型", font4ValueBold)));
		PDFPCell orgType =new PDFPCell(new Paragraph((String) dataMap.get("enterpriseType"), font4Value));
		orgType.setColspan(3);
		pdfPTable.addCell(orgType);

		pdfPTable.addCell(new PDFPCell(new Paragraph("住所", font4ValueBold)));
		PDFPCell addr =new PDFPCell(new Paragraph((String) dataMap.get("orgAddress"), font4Value));
		addr.setColspan(5);
		pdfPTable.addCell(addr);

		PDFPCell emptyRow =new PDFPCell(new Paragraph(" ", font4ValueBold));
		emptyRow.setColspan(7);
		pdfPTable.addCell(emptyRow);

		return pdfPTable;
	}

	private static PdfPTable writerPlantformRegForPayLog(Map dataMap) throws Exception {
		int[] colWidth = new int[]{15,30,30,30,15,15,15};
		PdfPTable pdfPTable = new PdfPTable(colWidth.length);
		pdfPTable.setWidths(colWidth);
		pdfPTable.setWidthPercentage(100);
		pdfPTable.setSpacingBefore(0);

		PDFPCell colTitle = new PDFPCell(new Paragraph("平台注册信息", font4SecValue));
		colTitle.setRowspan(3);
		pdfPTable.addCell(colTitle);

		pdfPTable.addCell(new PDFPCell(new Paragraph("机构名称", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) dataMap.get("orgName"), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("统一社会信用代码", font4ValueBold)));
		PDFPCell creditCode =new PDFPCell(new Paragraph((String) dataMap.get("orgCode"), font4Value));
		creditCode.setColspan(3);
		pdfPTable.addCell(creditCode);

		pdfPTable.addCell(new PDFPCell(new Paragraph("法定代表人/负责人姓名", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) dataMap.get("corporation"), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("企业类型", font4ValueBold)));
		PDFPCell orgType =new PDFPCell(new Paragraph((String) dataMap.get("enterpriseType"), font4Value));
		orgType.setColspan(3);
		pdfPTable.addCell(orgType);

		pdfPTable.addCell(new PDFPCell(new Paragraph("住所", font4ValueBold)));
		PDFPCell addr =new PDFPCell(new Paragraph((String) dataMap.get("orgAddress"), font4Value));
		addr.setColspan(5);
		pdfPTable.addCell(addr);

		PDFPCell emptyRow =new PDFPCell(new Paragraph(" ", font4ValueBold));
		emptyRow.setColspan(7);
		pdfPTable.addCell(emptyRow);

		return pdfPTable;
	}

	private static PdfPTable writerShareInfo(Map dataMap) throws Exception {
		int[] colWidth = new int[]{15,30,30,30,15,15,15};
		PdfPTable pdfPTable = new PdfPTable(colWidth.length);
		pdfPTable.setWidths(colWidth);
		pdfPTable.setWidthPercentage(100);
		pdfPTable.setSpacingBefore(0);

		PDFPCell colTitle = new PDFPCell(new Paragraph("政务共享信息", font4SecValue));
		colTitle.setRowspan(15);
		pdfPTable.addCell(colTitle);

		pdfPTable.addCell(new PDFPCell(new Paragraph("信息来源", font4ValueBold)));
		PDFPCell source =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("source")), font4Value));
		source.setColspan(5);
		pdfPTable.addCell(source);
		PDFPCell title1 =new PDFPCell(new Paragraph("一、基本信息", font4ValueBold));
		title1.setColspan(6);
		pdfPTable.addCell(title1);

		pdfPTable.addCell(new PDFPCell(new Paragraph("医保定点机构名称", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("orgNameYbj")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("统一社会信用代码", font4ValueBold)));
		PDFPCell creditCode =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("orgCodeYbj")), font4Value));
		creditCode.setColspan(3);
		pdfPTable.addCell(creditCode);

		pdfPTable.addCell(new PDFPCell(new Paragraph("医保定点机构代码", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("orgNo")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("法定代表人", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("comName")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("主要负责人", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("director")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("地址", font4ValueBold)));
		PDFPCell addr =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("ybjAddress")), font4Value));
		addr.setColspan(5);
		pdfPTable.addCell(addr);

		pdfPTable.addCell(new PDFPCell(new Paragraph("经济类型", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("economicType")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("经营性质", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("bizNature")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("隶属关系", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("affiliation")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("医疗机构类别", font4ValueBold)));
		String tempOrgType = (String) McpConst.YbjOrgTypeDict.getVal(StringUtil.null2Blank(dataMap.get("orgType")));
		tempOrgType = SystemConst.EMPTY.equals(tempOrgType) ? (String)dataMap.get("orgType") : tempOrgType;
		pdfPTable.addCell(new PDFPCell(new Paragraph( tempOrgType, font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("床位数", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("bedNum")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("医院等级", font4ValueBold)));
		String tempOrgClass = (String) McpConst.YbjOrgClassDict.getVal(StringUtil.null2Blank(dataMap.get("orgClass"))) ;
		tempOrgClass = SystemConst.EMPTY.equals(tempOrgClass) ? (String)dataMap.get("orgClass") : tempOrgClass;
		pdfPTable.addCell(new PDFPCell(new Paragraph(tempOrgClass, font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("收费等级", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("feeLevel")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("医院等次", font4ValueBold)));
		PDFPCell hoslevel =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("orgGrade")), font4Value));
		hoslevel.setColspan(3);
		pdfPTable.addCell(hoslevel);

		pdfPTable.addCell(new PDFPCell(new Paragraph("诊疗科目", font4ValueBold)));
		PDFPCell zhenliaokemu =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("bizSubject")), font4Value));
		zhenliaokemu.setColspan(5);
		pdfPTable.addCell(zhenliaokemu);

		pdfPTable.addCell(new PDFPCell(new Paragraph("执业许可证号", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("proLicenseNo")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("执业许可有效期限", font4ValueBold)));
		PDFPCell licence =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("prolicNoTimeLimit")), font4Value));
		licence.setColspan(3);
		pdfPTable.addCell(licence);

		PDFPCell title2 =new PDFPCell(new Paragraph("二、医保服务协议信息", font4ValueBold));
		title2.setColspan(6);
		pdfPTable.addCell(title2);

		pdfPTable.addCell(new PDFPCell(new Paragraph("批准建档时间", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("approveTime")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("批准文号", font4ValueBold)));
		PDFPCell wenhao =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("approveNo")), font4Value));
		wenhao.setColspan(3);
		pdfPTable.addCell(wenhao);

		pdfPTable.addCell(new PDFPCell(new Paragraph("定点机构有效性", font4ValueBold)));
		String tempValidFlag = (String) McpConst.YbjValidFlagDict.getVal(StringUtil.null2Blank(dataMap.get("validFlag")));
		tempValidFlag = SystemConst.EMPTY.equals(tempValidFlag) ? (String)dataMap.get("validFlag") : tempValidFlag;
		pdfPTable.addCell(new PDFPCell(new Paragraph(tempValidFlag, font4Value)));
		
		pdfPTable.addCell(new PDFPCell(new Paragraph("医保区划", font4ValueBold)));
		PDFPCell area =new PDFPCell(new Paragraph(StringUtil.null2Blank(dataMap.get("bizArea")), font4Value));
		area.setColspan(3);
		pdfPTable.addCell(area);

		pdfPTable.addCell(new PDFPCell(new Paragraph("医保服务协议有效期开始日期", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("validStartDate")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("医保服务协议有效期截止日期", font4ValueBold)));
		PDFPCell enddate =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("validEndDate")), font4Value));
		enddate.setColspan(3);
		pdfPTable.addCell(enddate);

		pdfPTable.addCell(new PDFPCell(new Paragraph("医保评级", font4ValueBold)));
		pdfPTable.addCell(new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("miGrade")), font4Value)));

		pdfPTable.addCell(new PDFPCell(new Paragraph("结算支持类型", font4ValueBold)));
		PDFPCell supportType =new PDFPCell(new Paragraph((String) StringUtil.null2Blank(dataMap.get("payType")), font4Value));
		supportType.setColspan(3);
		pdfPTable.addCell(supportType);

		return pdfPTable;
	}

	private static PdfPTable writerTable(int[] colWidth, String[] colNames, String[] datas, int colNamesAlignment, int colDataAlignment) throws Exception {
		PdfPTable pdfPTable = new PdfPTable(colWidth.length);
		pdfPTable.setWidths(colWidth);
		pdfPTable.setWidthPercentage(100);
		pdfPTable.setSpacingBefore(0);
		
		PDFPCell accountcell = null;
		
		boolean linkFlag = false;
		
		if(colNames != null) {
			for(String title:colNames) {
				if("主体信息汇总表".equals(title)) {linkFlag = true;}
				accountcell = new PDFPCell(new Paragraph(title, font4ValueBold));
				accountcell.setHorizontalAlignment(colNamesAlignment);		
				pdfPTable.addCell(accountcell);
			}
		}
		
		if(datas != null) {
			for(int i=0;i<datas.length;i++) {
				String data = datas[i];
				if("null".equals(datas[i]) || StringUtils.isBlank(datas[i])) {
					data = " ";
				}
				
				Paragraph paragraph = new Paragraph();
				
				if(i==3 && linkFlag) {
					Anchor link = new Anchor(data, font4Value);
					link.setReference("#link");
					paragraph.add(link);
				}else {
					paragraph = new Paragraph(data, font4Value);
				}
				
				accountcell = new PDFPCell(paragraph);
				accountcell.setHorizontalAlignment(colDataAlignment);		
				pdfPTable.addCell(accountcell);
			}
		}
		
		return pdfPTable;
	}
	
	
	
	public static String buildAuthPDF(AuthDTO authDTO, String dirPath) throws Exception {
		
		File f = new File(dirPath);
		if((!f.exists())||(!f.isDirectory())){
			f.mkdirs();
		}
		
		
		String pdfPath = dirPath+authDTO.getAuthNo()+".pdf";
		String pdfPathTemp = dirPath+authDTO.getAuthNo()+"_temp.pdf";
		
		File pdf = new File(pdfPathTemp);  // 定义PDF 生成文件(主要是路径)
		
		Document doc = new Document();
		PdfWriter.getInstance(doc,new FileOutputStream(pdf));	
		doc.setPageSize(PageSize.A4);
		doc.setMargins(30, 30, 30, 30);
		
		
		BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
		Font font2Title = new Font(bf, 26, Font.BOLD);
		Font font2Name = new Font(bf, 18, Font.BOLD);
		Font font2Value = new Font(bf, 18, Font.NORMAL);
		
		try {
			
			doc.open();
			   
			Paragraph paragraph = new Paragraph("医保信息查询授权书", font2Title);
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph.add(Chunk.NEWLINE);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("授权书编号："+authDTO.getAuthNo(), font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph(25, "授权人：", font2Name);
			Chunk miOrgName = new Chunk(authDTO.getMiOrgName(), font2Value);
			paragraph.add(miOrgName);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(25, "被授权人：", font2Name);
			Chunk bankName = new Chunk(authDTO.getBankName(), font2Value);
			paragraph.add(bankName);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph(25);
			Chunk chunk1 = new Chunk("为获取融资服务，现授权"+authDTO.getBankName()+"（统一社会信用代码"+authDTO.getBankOrgCode()+"）通过", font2Value);
			Chunk chunk2 = new Chunk("中征应收账款融资服务平台", font2Name);
			Chunk chunk3 = new Chunk("查询、收集与我方有关的全部信息，包括但不限于：", font2Value);
			paragraph.add(chunk1);
			paragraph.add(chunk2);
			paragraph.add(chunk3);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("1.医疗保障局共享的机构主体、医保合作协议、医保结算信息等；", font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("2.卫生健康委员会共享的机构主体、许可证、经营概况等信息；", font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("3.市场监督管理局共享的机构主体信息；", font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("4.其他行政处罚信息；", font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("授权期限："+authDTO.getAuthStartTimeStr()+"至"+authDTO.getAuthEndTimeStr(), font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("被授权人可对上述信息进行合理的使用，并可将上述信息传递给相关单位进行核验。为确保信息安全，被授权人应采取有效措施并承担保密义务。", font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph(authDTO.getMiOrgName(), font2Name);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);
			
			paragraph = new Paragraph("签署日期："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(authDTO.getAuthCreateTime()), font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (doc != null) {
				doc.close();
			}
		}
		

		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pdfPath));
        setWatermark(bos, pdfPathTemp);
		
		bos.close();
		File ff = new File(pdfPathTemp);
		if(ff.exists()) {
			ff.delete();
		}
		
		return pdfPath;
	}


	public static String buildAuthPDFByYBD(AuthDTO authDTO, String dirPath) throws Exception {

		File f = new File(dirPath);
		if((!f.exists())||(!f.isDirectory())){
			f.mkdirs();
		}


		String pdfPath = dirPath+authDTO.getAuthNo()+".pdf";
		String pdfPathTemp = dirPath+authDTO.getAuthNo()+"_temp.pdf";

		File pdf = new File(pdfPathTemp);  // 定义PDF 生成文件(主要是路径)

		Document doc = new Document();
		PdfWriter.getInstance(doc,new FileOutputStream(pdf));
		doc.setPageSize(PageSize.A4);
		doc.setMargins(30, 30, 30, 30);
		
		
		
		BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
		Font font2Title = new Font(bf, 22, Font.BOLD);
		Font font2Name = new Font(bf, 14, Font.BOLD);
		Font font2Value = new Font(bf, 14, Font.NORMAL);

		try {

			doc.open();

			Paragraph paragraph = new Paragraph("医保信息查询授权书", font2Title);
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);
			paragraph.add(Chunk.NEWLINE);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph("授权书编号："+authDTO.getAuthNo(), font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph.add(Chunk.NEWLINE);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(35, "授权人："+authDTO.getMiOrgName(), font2Name);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(35, "被授权人："+authDTO.getBankName(), font2Name);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(35);
			Chunk chunk1 = new Chunk("为获取融资服务，现授权"+authDTO.getBankName()+"（统一社会信用代码："+authDTO.getBankOrgCode()+"）通过", font2Value);
			Chunk chunk2 = new Chunk("中征应收账款融资服务平台", font2Name);
			Chunk chunk3 = new Chunk("查询、收集与我方有关的信息，包括但不限于：", font2Value);
			paragraph.add(chunk1);
			paragraph.add(chunk2);
			paragraph.add(chunk3);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(35, "1.医疗保障局共享的定点机构主体信息；", font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(35, "2.医疗保障局共享的定点机构结算账户信息；", font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(35, "3.医疗保障局共享的定点机构结算数据；", font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(35, "4.违反医保服务协议约定的事项以及违约处罚内容；", font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(35, "5.其他行政处罚信息。", font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(35, "授权期限："+authDTO.getAuthStartTimeStr()+"至"+authDTO.getAuthEndTimeStr(), font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(35, "被授权人可对上述信息进行合理的使用，并可将上述信息传递给相关单位进行核验。为确保信息安全，被授权人应采取有效措施并承担保密义务。", font2Value);
			paragraph.setAlignment(Paragraph.ALIGN_LEFT);
			paragraph.setFirstLineIndent(35);
			paragraph.add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(35, "授权人："+authDTO.getMiOrgName(), font2Name);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);

			paragraph = new Paragraph(35, "签署日期："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(authDTO.getAuthCreateTime()), font2Name);
			paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
			paragraph .add(Chunk.NEWLINE);
			doc.add(paragraph);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (doc != null) {
				doc.close();
			}
		}


		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pdfPath));
        setWatermark(bos, pdfPathTemp);

		bos.close();
		File ff = new File(pdfPathTemp);
		if(ff.exists()) {
			ff.delete();
		}

		return pdfPath;
	}



	/**
	 *
	 * @param input         原PDF位置
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static void setWatermark(BufferedOutputStream bos, String input) throws DocumentException, IOException {


		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			InputStream in = PDFUtil.class.getClassLoader().getResourceAsStream("mcp/images/waterMarkA4.jpg");

			PdfReader reader = new PdfReader(input);
			PdfStamper stamper = new PdfStamper(reader, bos);
			int total = reader.getNumberOfPages() + 1;
			PdfContentByte content;
			BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
			PdfGState gs = new PdfGState();


			byte[] buffer = new byte[1024];
			for (int readNum; (readNum = in.read(buffer)) >0;) {
				baos.write(buffer, 0, readNum);
			}
			byte[] bytes = baos.toByteArray();
			for (int i = 1; i < total; i++) {
				//	        content = stamper.getOverContent(i);// 在内容上方加水印
				content = stamper.getUnderContent(i);// 在内容下方加水印
				content.saveState();
				float X = reader.getPageSize(i).getWidth();
				float Y = reader.getPageSize(i).getHeight();
				gs.setFillOpacity(2.5f);
				content.setGState(gs);
				content.beginText();
				Image image = Image.getInstance(bytes);
				image.scalePercent(50.8f);
				image.setAbsolutePosition(0, 0);
				content.setFontAndSize(base, 8);
				image.setRotationDegrees(0);// 旋转
				image.setAbsolutePosition(0, 0);
				image.scaleAbsolute(X, Y);
				content.setColorFill(BaseColor.BLACK);
				content.setGState(gs);
				content.addImage(image);
				content.endText();
			}
			baos.close();
			in.close();
			stamper.close();
			reader.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 *
	 * @param input         原PDF位置
	 * @throws Exception
	 */
	public static void setWatermark(FileOutputStream bos, String input) throws Exception {
		PdfReader reader = new PdfReader(input);
		PdfStamper stamper = new PdfStamper(reader, bos);
		int total = reader.getNumberOfPages() + 1;
		PdfContentByte content;
		Image image = getImage("waterMarkA4.jpg");
		PdfGState gs = new PdfGState();
		for (int i = 1; i < total; i++) {
			content = stamper.getOverContent(i);// 在内容上方加水印
//			content = stamper.getUnderContent(i);// 在内容下方加水印
			content.saveState();
			float X=reader.getPageSize(i).getWidth();
			float Y=reader.getPageSize(i).getHeight();
			gs.setFillOpacity(0.7f);
			content.setGState(gs);
			image.setAbsolutePosition(0, 0);
			image.scaleAbsolute(X, Y);
			content.addImage(image);
			content.restoreState();// 注意这里必须调用一次restoreState 否则设置无效
		}
		stamper.close();
	}


	/**
	 * 获取路径下的图片信息-
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	private static Image getImage(String fileName) throws Exception {
		InputStream img = null;
		ByteArrayOutputStream bos = null;
		try {
			img = PDFUtil.class.getResourceAsStream(fileName);
			bos = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			for (int readNum; (readNum = img.read(buf)) != -1;) {
				bos.write(buf, 0, readNum);
			}
			byte[] bytes = bos.toByteArray();
			return Image.getInstance(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (img != null) {
				img.close();
			}
			if (bos != null) {
				bos.close();
			}
		}
		return null;
	}


	/**
	 * 添加图片和文字水印
	 *
	 * @param srcFile    待加水印文件
	 * @param destFile   加水印后存放地址
	 * @param text       加水印的文本内容
	 * @param textWidth  文字横坐标
	 * @param textHeight 文字纵坐标
	 * @param imgFile    加水印图片文件
	 * @param imgWidth   图片横坐标
	 * @param imgHeight  图片纵坐标
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static void setWatermark(String srcFile, String destFile, String text, int textWidth, int textHeight,
									String imgFile, int imgWidth, int imgHeight) throws IOException, DocumentException {

		// 待加水印的文件
		PdfReader reader = new PdfReader(srcFile);

		// 加完水印的文件
		PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));

		// 设置字体
		BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

		// PDF总页数
		int total = reader.getNumberOfPages() + 1;

		// 循环对每页插入水印
		PdfContentByte content;
		for (int i = 1; i < total; i++) {

			// 水印在之前文本之上
			content = stamper.getOverContent(i);

			// 图片水印
			if (imgFile != null) {

				Image image = null;
				if (imgFile != null) {

					image = Image.getInstance(imgFile);
					image.setAbsolutePosition(imgWidth, imgHeight);

					// 设置图片的显示大小
					image.scaleToFit(100, 125);
				}

				content.addImage(image);
			}

			// 文字水印
			if (text != null) {

				content.beginText();


				// 设置颜色 默认为蓝色
				content.setColorFill(BaseColor.BLUE);

				// 设置字体及字号
				content.setFontAndSize(font, 38);

				// 设置起始位置
				content.setTextMatrix(textWidth, textHeight);

				// 中间水印
				content.showTextAligned(Element.ALIGN_LEFT, text, textWidth, textHeight, 45);

				// 底部水印
				for (int k = 0; k < text.length(); k++) {

					// 距离底边的距离
					content.setTextRise(10);

					// 将char转成字符串
					content.showText(String.valueOf(text.charAt(k)));
				}

				content.endText();
			}
		}

		stamper.close();
	}



	/**
	 * 根据模板创建生成pdf
	 * @param map 模板中的表单数据 key-表单属性值；value-值
	 * @param templatePath 模板路径
	 * @return 返回生成的pdf文件路径
	 */
	public static String createPdfByTemplate(Map<String,Object> map, String templatePath, String newPdfPath) {
		PdfReader reader;
		ByteArrayOutputStream bos;
		PdfStamper stamper;
		//生成的pdf文件存放地址 要确保文件夹的存在
		System.out.println(newPdfPath);
		try {
			File docPath = new File(newPdfPath.substring(0, newPdfPath.lastIndexOf("/")));
			if(!docPath.exists()){
				docPath.mkdirs();
			}


			//设置字体是必须要的，不然没法向模板pdf里写值
			//用以支持中文
			BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			// 读取pdf模板
			reader = new PdfReader(templatePath);
			bos = new ByteArrayOutputStream();
			stamper = new PdfStamper(reader, bos);
			//拿到pdf模板中的表单属性
			AcroFields form = stamper.getAcroFields();
			//设置字体
			form.addSubstitutionFont(bfChinese);
			java.util.Iterator<String> it = form.getFields().keySet().iterator();
			//遍历表单属性，对每个属性赋值
			while (it.hasNext()) {
				String name = it.next().toString();
				Object o =  map.get(name);
				String value = o == null ? null : o.toString();
				if(value == null){
					continue;
				}
				form.setField(name,value);
			}
			// 如果为false那么生成的PDF文件还能编辑，一定要设为true
			stamper.setFormFlattening(true);
			bos.close();
			stamper.close();

			Document doc = new Document();
			File file = new File(newPdfPath);
			PdfCopy copy = new PdfCopy(doc, new FileOutputStream(file));
			doc.open();
			PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
			copy.addPage(importPage);
			doc.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new BaseException("生成pdf失败-IOException，请联系管理员");
		} catch (DocumentException e) {
			throw new BaseException("生成pdf失败-DocumentException，请联系管理员");
		}
		return newPdfPath;
	}


	/*** 合并pdf*
	 * @param files 要合并的pdf文件*
	 * @param newfile 生成的文件名*
	 * @return
	 */
	@Deprecated
	public static Boolean mergePdfFiles(String[] files, String newfile) {
		Boolean retValue = false;
		Document document = null;
		try {
			document = new Document(new PdfReader(files[0]).getPageSize(1));
			PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
			document.open();
			for (int i = 0; i < files.length; i++) {
				PdfReader reader = new PdfReader(files[i]);
				int n = reader.getNumberOfPages();
				for (int j = 1; j <= n; j++) {
					document.newPage();
					PdfImportedPage page = copy.getImportedPage(reader, j);
					copy.addPage(page);
				}
			}
			retValue = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			document.close();
		}

		return retValue;
	}


	// 图片水印处理类
	public static class ImageWatermark extends PdfPageEventHelper {
		private final Image watermarkImage;

		public ImageWatermark(Image watermarkImage) {
			this.watermarkImage = watermarkImage;
		}

		@Override
		public void onEndPage(PdfWriter writer, Document document) {
			try {
				// 获取PDF内容层
				PdfContentByte canvas = writer.getDirectContentUnder();

				// 计算水印位置（居中）
				Rectangle pageSize = document.getPageSize();
				float x = (pageSize.getWidth() - watermarkImage.getScaledWidth());
				float y = (pageSize.getHeight() - watermarkImage.getScaledHeight());

				// 设置水印位置和透明度
				watermarkImage.setAbsolutePosition(x, y);

				// 添加水印到每页
				canvas.addImage(watermarkImage);

			} catch (Exception e) {
				throw new RuntimeException("图片水印添加失败", e);
			}
		}
	}

}
class PDFTable extends com.lowagie.text.pdf.PdfPTable {

	/**
	 * @param columns
	 *            表的列数
	 */
	public PDFTable(int columns) {
		super(columns);
		setWidthPercentage(100);
		setSpacingBefore(0);
	}

	/**
	 * @param columns
	 *            表的列数
	 */
	public PDFTable(int columns, int width) {
		super(columns);
		setWidthPercentage(width);
		setSpacingBefore(0);
	}
}

class PDFPCell extends com.itextpdf.text.pdf.PdfPCell {

	private static final Logger logger = LoggerFactory.getLogger(PDFPCell.class);

	/*
	 * 定义输出Cell的所有Border;
	 */
	private static int DEFAULT_BORDER = Cell.LEFT | Cell.RIGHT | Cell.TOP | Cell.BOTTOM;

	// private static int DEFAULT_BORDER = 0;

	// private static int DEFUALT_PADDING = 5;

	/**
	 * CPBPdfPCell类构造器
	 *
	 *
	 */
	public PDFPCell() {
		super();
		this.border = DEFAULT_BORDER;
		this.setPadding(5);
		this.setSpaceCharRatio(5);
	}

	/**
	 * @param arg0
	 *            输入参数为Phrase对象
	 */
	public PDFPCell(Phrase arg0) {
		super(arg0);

		this.border = DEFAULT_BORDER;
		this.setPadding(5);
		this.setSpaceCharRatio(5);
		this.setPaddingTop(2);
		this.setVerticalAlignment(ALIGN_MIDDLE);
		if (arg0.getFont().equals(McpPdfUtil.font4Value)) {
			this.setPaddingTop(0);
			this.setLeading(-3, 1.5f);
		}
	}

	/**
	 * @param arg0
	 *            输入参数为Image对象
	 */
	public PDFPCell(Image arg0) {
		super(arg0);
		this.border = DEFAULT_BORDER;
	}

	/**
	 * @param arg0
	 *            输入参数为PdfPTable对象
	 */
	public PDFPCell(PdfPTable arg0) {
		super(arg0);
		this.border = DEFAULT_BORDER;
	}

	/**
	 * @param arg0
	 *            输入参数为PdfPCell实例
	 */
	public PDFPCell(com.itextpdf.text.pdf.PdfPCell arg0) {
		super(arg0);
		this.border = DEFAULT_BORDER;
	}

	/**
	 * @param arg0
	 *            输入参数为Image实例
	 * @param arg1
	 *            输入参数为boolean值
	 */
	public PDFPCell(Image arg0, boolean arg1) {
		super(arg0, arg1);
		this.border = DEFAULT_BORDER;
	}

}
